package com.ctshk.rpc.order.localfun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.vo.OrderRefundDTO;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.localfun.dto.LocalFunOrderRefundListDTO;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrder;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrderRefund;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderMapper;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderRefundMapper;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderRefundReq;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderRefundUpdateReq;
import com.ctshk.rpc.order.localfun.service.ILocalFunOrderRefundService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 门票退款记录 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-24
 */
@DubboService
public class LocalFunOrderRefundServiceImpl extends ServiceImpl<LocalFunOrderRefundMapper, LocalFunOrderRefund> implements ILocalFunOrderRefundService {

    @Autowired
    private LocalFunOrderRefundMapper localFunOrderRefundMapper;
    @DubboReference
    private ISysUserService iSysUserService;
    @DubboReference
    private IFinanceBillService iFinanceBillService;
    @Autowired
    private LocalFunOrderMapper localFunOrderMapper;

    /**
     * 订单操作退款记录
     *
     * @param scenicOrderRefundReq
     * @return LocalFunOrderRefundListDTO
     */
    @Override
    public Result<List<LocalFunOrderRefundListDTO>> list(LocalFunOrderRefundReq scenicOrderRefundReq) {
        QueryWrapper<LocalFunOrderRefund> scenicOrderRefundQueryWrapper = new QueryWrapper<>();
        scenicOrderRefundQueryWrapper.eq("is_deleted",0);
        scenicOrderRefundQueryWrapper.eq("order_id",scenicOrderRefundReq.getOrderId());
        List<LocalFunOrderRefund> list = localFunOrderRefundMapper.selectList(scenicOrderRefundQueryWrapper);
        List<LocalFunOrderRefundListDTO> scenicOrderRefundListDTOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(LocalFunOrderRefund scenicOrderRefund : list){
                LocalFunOrderRefundListDTO scenicOrderTouristDTO = EntityUtil.copy(scenicOrderRefund,LocalFunOrderRefundListDTO.class);
                //todo   上线去掉
                UserDTO userDTO = null;
                try {
                    userDTO = iSysUserService.loadUserByParam(scenicOrderRefund.getCreateId(), 1);
                    //申请人
                    scenicOrderTouristDTO.setCreateName(userDTO.getUsername());
                } catch (Exception e) {
                    throw new BusinessException(SystemError.USER_1002);
                }
                scenicOrderTouristDTO.setCurrency(scenicOrderRefund.getCurrency());
                scenicOrderRefundListDTOS.add(scenicOrderTouristDTO);
            }
        }
        return Result.success(scenicOrderRefundListDTOS);
    }

    @Override
    public Result<List<OrderRefundDTO>> refundRecords(Long orderId) {
        QueryWrapper<LocalFunOrderRefund> scenicOrderRefundQueryWrapper = new QueryWrapper<>();
        scenicOrderRefundQueryWrapper.eq("is_deleted",0);
        scenicOrderRefundQueryWrapper.eq("order_id",orderId);
        List<LocalFunOrderRefund> list = localFunOrderRefundMapper.selectList(scenicOrderRefundQueryWrapper);
        List<OrderRefundDTO> orderRefundDTOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            orderRefundDTOS = list.stream().map(entity->{
                OrderRefundDTO dto = new OrderRefundDTO();
                dto.setApprovalAmount(entity.getActualRefundAmount());
                dto.setBusinessType(SystemBusinessType.LOCAL_FUN.getCode());
                dto.setCurrency(entity.getCurrency());
                dto.setRefundAccount(entity.getRefundAccount());
                dto.setPaidInAmount(entity.getActualRefundAmount());
                dto.setRefundAmount(entity.getRefundAmount());
                dto.setRefundId(entity.getId());
                dto.setRefundNumber(entity.getRefundNumber());
                dto.setRefundDetail(CollectionTypeIdCode.FULL.getMsg());
                dto.setRefundReason(entity.getRefundReason());
                dto.setRefundType(entity.getRefundWay());
                dto.setRemark(entity.getRemark());
                dto.setTotalReceivables(entity.getRefundAmount());
                return dto;
            }).collect(Collectors.toList());
        }
        return Result.success(orderRefundDTOS);
    }

    @Override
    public Result<Long> refund(LocalFunOrderRefundUpdateReq scenicOrderRefundUpdateReq, TokenUser tokenUser) {

        LocalFunOrder localFunOrder = localFunOrderMapper.selectById(scenicOrderRefundUpdateReq.getOrderId());
        if (localFunOrder == null) {
            //订单不存在
            throw new BusinessException(SystemError.LOCAL_FUN_18010);
        }
        if (!(localFunOrder.getCancelStatus() == ApprovalStatus.REVIEW_YES.getCode())) {
            //审批成功状态的订单，才可以做确认退款操作
            throw new BusinessException(SystemError.SHIP_PRODUCT_11033);
        }

        QueryWrapper<LocalFunOrderRefund> shipOrderRefundQueryWrapper = new QueryWrapper<>();
        shipOrderRefundQueryWrapper.lambda().eq(LocalFunOrderRefund::getOrderId, localFunOrder.getId());

        List<LocalFunOrderRefund> shipOrderRefundList = localFunOrderRefundMapper.selectList(shipOrderRefundQueryWrapper);
        boolean ifAllRefund = true;
        for (LocalFunOrderRefund shipOrderRefund : shipOrderRefundList) {
            if (scenicOrderRefundUpdateReq.getId().equals(shipOrderRefund.getId())) {
                // 确认退款
                shipOrderRefund.setStatus(ApprovalStatus.REFUND_SUCCESS.getCode());
                localFunOrderRefundMapper.updateById(shipOrderRefund);

                //財務-操作退款
                if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(shipOrderRefund.getRefundNumber())){
                    BillOperateRefundReq billOperateRefundReq = new BillOperateRefundReq();
                    billOperateRefundReq.setBillNumber(shipOrderRefund.getRefundNumber());
                    billOperateRefundReq.setBusinessType(SystemBusinessType.LOCAL_FUN.getCode());
                    billOperateRefundReq.setUserId(tokenUser.getId());

                    iFinanceBillService.operateRefund(billOperateRefundReq);
                }
            }
            /**
             * do something暂无支付方式主数据，5-银行优惠，会员积分，优惠券，
             * 除5以外的支付方式记录的状态，有一个不是退款成功，ifAllRefund为false
             */
            if (!(shipOrderRefund.getRefundWayId() == 5) && !(shipOrderRefund.getStatus() == OrderRefundStatus.REFUND_SUCCESSFUL.getCode())) {
                ifAllRefund = false;
            }
        }
        if (ifAllRefund) {
            // 全部已退款,更新状态
            localFunOrder.setCancelStatus(ApprovalStatus.REFUND_SUCCESS.getCode());
            localFunOrder.setScheduledStatus(null);
            localFunOrder.setRefundSuccessDate(LocalDateTime.now());
            localFunOrderMapper.updateById(localFunOrder);
        }
        return Result.success(Long.valueOf(scenicOrderRefundUpdateReq.getOrderId()));
    }

    @Override
    public Result confirmRefund(String refundNumber, Long userId) {
        LocalFunOrderRefund airportExpressOrderRefund = localFunOrderRefundMapper.selectOne(Wrappers.<LocalFunOrderRefund>lambdaQuery()
                .eq(LocalFunOrderRefund::getRefundNumber, refundNumber));
        if (airportExpressOrderRefund == null) {
            //收款记录不存在
            return Result.failed(SystemError.LOCAL_FUN_18024);
        }
        airportExpressOrderRefund.setStatus(ApprovalStatus.REFUND_SUCCESS.getCode());
        airportExpressOrderRefund.setModifiedId(userId);
        airportExpressOrderRefund.setGmtModified(LocalDateTime.now());
        localFunOrderRefundMapper.updateById(airportExpressOrderRefund);

        LocalFunOrder localFunOrder = localFunOrderMapper.selectById(airportExpressOrderRefund.getOrderId());
        if(localFunOrder != null){
            localFunOrder.setRefundSuccessDate(LocalDateTime.now());
            localFunOrderMapper.updateById(localFunOrder);
        }
        return Result.success();
    }
}
